import { getToken, setToken, delToken } from '@/utils/token'
import { reqGetUserInfo, reqLogout } from '@/api'

let state = {
  token: getToken() || '',
  userInfo: {}
}

let mutations = {
  SETTOKEN(state, token) {
    state.token = token
  },
  SETUSERINFO(state, data) {
    state.userInfo = data
  },
  DELUSERINFO(state, data) {
    state.userInfo = {}
  },
  DELTOKEN(state) {
    state.token = ''
  }
}

let actions = {
  // token
  setToken({ commit }, token) {
    if (token) {
      commit('SETTOKEN', token)
      // 本地存储
      setToken(token)
    }
  },

  // 获取用户信息
  async getUserInfo({ commit }) {
    let result = await reqGetUserInfo()
    if (result.code == 200) {
      commit('SETUSERINFO', result.data)
      return { ok: true, msg: '' }
    } else {
      return { ok: false, msg: result.message }
    }
  },
  // 退出登陆
  async logout({ commit }) {
    const result = await reqLogout()
    if (result.code == 200) {
      // 清除本地用户信息
      commit('DELUSERINFO')
      //清除token
      commit('DELTOKEN')
      delToken()
      return { ok: true, msg: '' }
    } else {
      return { ok: false, msg: result.message }
    }
  }
}

let getters = {}

export default {
  state,
  mutations,
  actions,
  getters
}
